﻿using Gj;
using NaughtyAttributes;
using UnityEngine;

public class ViewSize : NodeSize
{
    public Camera camera;
    public float max;
    public float min;
    public bool proportional;
    public bool main;

    [Slider(0.1f, 1f)] public float ratio = 1;

    public int width;
    public int height;

    protected override void OnRefresh(float rw, float rh, float w, float h, float s)
    {
        if (proportional)
            camera.fieldOfView = MathTools.linear(min, max, h / rh);
        else
            camera.fieldOfView = MathTools.linear(min, max, GetRatio(rw, rh, w, h));

        if (main) SystemInput.view = camera.fieldOfView;
    }

    protected float GetRatio(float rw, float rh, float w, float h)
    {
        var v1 = rw / rh;
        var v2 = rh / rw;
        var v = w / h;
        if (v < v1) return 0;
        if (v > v2) return 1;
        return (v - v1) / (v2 - v1);
    }

    [Button]
    public void UpdateScale()
    {
        ScalableBufferManager.ResizeBuffers(ratio, ratio);
    }

    [Button]
    public void UpdateResolution()
    {
        Screen.SetResolution(width, height, true, 30);
    }

    [Button]
    public void Console()
    {
        Debug.LogErrorFormat("width:{0} height:{1} rWidth:{2} rHeight:{3} rate:{4}", Screen.width, Screen.height,
            Screen.currentResolution.width, Screen.currentResolution.height, Screen.currentResolution.refreshRateRatio);
    }
}